import java.io.IOException;
import java.io.PrintWriter;
import java.util.HashMap;

import javax.servlet.ServletConfig;
import javax.servlet.ServletException;
import javax.servlet.http.HttpServlet;
import javax.servlet.http.HttpServletRequest;
import javax.servlet.http.HttpServletResponse;

public class GetStocksInfo extends HttpServlet {
	private HashMap<String, Stock> stocks;

	protected void doGet(HttpServletRequest httpServletRequest, HttpServletResponse httpServletResponse)
			throws ServletException, IOException {
		double sz = Math.random() * 20;
		double pf = Math.random() * 0.5;

		boolean flagsz = ((int) (Math.random() * 10)) % 2 == 0;
		boolean flagpf = ((int) (Math.random() * 10)) % 2 == 0;

		Stock szzs = stocks.get("300001");
		Stock pfyh = stocks.get("000001");
		double temp;
		if (flagsz) {
			temp = szzs.getNow() + sz;
		} else {
			temp = szzs.getNow() - sz;
		}
		temp = (int) (temp * 100) / 100.0;
		szzs.setNow(temp);
		if (flagpf) {
			temp = pfyh.getNow() + pf;
		} else {
			temp = pfyh.getNow() - pf;
		}
		temp = (int) (temp * 100) / 100.0;
		pfyh.setNow(temp);

		httpServletResponse.setContentType("text/html;charset=utf-8");
		PrintWriter out = httpServletResponse.getWriter();
		StringBuilder builder = new StringBuilder();
		// 采用数组的方式回传两个股票对象
		/*
		 * builder.append("[{name:\"").append(szzs.getName()).append("\",id:\"")
		 * .append(szzs.getId())
		 * .append("\",yes:").append(szzs.getYesterday()).append(",tod:").append
		 * (szzs.getToday()) .append(",now:").append(szzs.getNow())
		 * .append("},")
		 * .append("{name:\"").append(pfyh.getName()).append("\",id:\"").append(
		 * pfyh.getId())
		 * .append("\",yes:").append(pfyh.getYesterday()).append(",tod:").append
		 * (pfyh.getToday()) .append(",now:").append(pfyh.getNow())
		 * .append("}]");
		 */
		// 采用对象的方式回传两个股票对象
		// 如果回传表示对象的json，需要在最外层加上一个括号，否则页面解析会出错
		builder.append("({").append("\"").append(szzs.getId()).append("\":{name:\"").append(szzs.getName())
				.append("\",yes:").append(szzs.getYesterday()).append(",tod:").append(szzs.getToday()).append(",now:")
				.append(szzs.getNow()).append("},").append("\"").append(pfyh.getId()).append("\":{name:\"")
				.append(pfyh.getName()).append("\",yes:").append(pfyh.getYesterday()).append(",tod:")
				.append(pfyh.getToday()).append(",now:").append(pfyh.getNow()).append("}})");
		out.println(builder);
	}

	protected void doPost(HttpServletRequest httpServletRequest, HttpServletResponse httpServletResponse)
			throws ServletException, IOException {
		doGet(httpServletRequest, httpServletResponse);
	}

	public void init(ServletConfig servletConfig) throws ServletException {
		stocks = new HashMap<String, Stock>();
		Stock szzs = new Stock(3000.0, 2990.1, "上证指数", "300001");
		Stock pfyh = new Stock(23.22, 23.50, "浦发银行", "000001");

		stocks.put(szzs.getId(), szzs);
		stocks.put(pfyh.getId(), pfyh);

		System.out.println(stocks);
	}
}
